package com.ruoyi.webs.utils.listener;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


public class SessionListener
        implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent sessionEvent) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = sessionEvent.getSession();
        ServletContext application = session.getServletContext();

        boolean flag = true;

        try {
            request.setCharacterEncoding("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String sessionId = session.getId();
        List<String> onlineUserList = (List) application.getAttribute("onlineUserList");


        if (onlineUserList == null) {
            onlineUserList = new ArrayList();
            application.setAttribute("onlineUserList", onlineUserList);
        } else {
            for (int i = 0; i < onlineUserList.size(); i++) {
                String exitsSessionId = onlineUserList.get(i);
                if (StringUtils.equals(exitsSessionId, sessionId)) {
                    flag = false;
                    break;
                }
            }
        }
        if (flag) {
            onlineUserList.add(sessionId);
        }
    }


    public void sessionDestroyed(HttpSessionEvent sessionEvent) {
        HttpSession session = sessionEvent.getSession();
        ServletContext application = session.getServletContext();
        String sessionId = session.getId();

        List onlineUserList = (List) application.getAttribute("onlineUserList");
        onlineUserList.remove(sessionId);
    }
}